package leetcode.editor.cn;
//给定两个整数数组 inorder 和 postorder ，其中 inorder 是二叉树的中序遍历， postorder 是同一棵树的后序遍历，请你构造并
//返回这颗 二叉树 。 
//
// 
//
// 示例 1: 
//
// 
//输入：inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
//输出：[3,9,20,null,null,15,7]
// 
//
// 示例 2: 
//
// 
//输入：inorder = [-1], postorder = [-1]
//输出：[-1]
// 
//
// 
//
// 提示: 
//
// 
// 1 <= inorder.length <= 3000 
// postorder.length == inorder.length 
// -3000 <= inorder[i], postorder[i] <= 3000 
// inorder 和 postorder 都由 不同 的值组成 
// postorder 中每一个值都在 inorder 中 
// inorder 保证是树的中序遍历 
// postorder 保证是树的后序遍历 
// 
// Related Topics 树 数组 哈希表 分治 二叉树 
// 👍 988 👎 0


//leetcode submit region begin(Prohibit modification and deletion)

import java.util.HashMap;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution84 {
    // 存储 inorder 中值到索引的映射
    HashMap<Integer, Integer> valToIndex = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++) {
            valToIndex.put(inorder[i], i);
        }

        // 根据函数定义，用 inorder 和 postorder 构造二叉树
        return build(inorder, 0, inorder.length - 1,
                postorder, 0, postorder.length - 1);
    }

    /**
     * build 函数的定义：
     * 若后序遍历数组为 postorder[preStart..preEnd]，[leftNode,....,rightNode,....,root]
     * 中序遍历数组为 inorder[inStart..inEnd]，[leftNode,....,root,rightNode,....]
     * 构造二叉树，返回该二叉树的根节点
     *
     * @param inorder
     * @param inLeft
     * @param inRight
     * @param postorder
     * @param postLeft
     * @param postRight
     * @return
     */
    private TreeNode build(int[] inorder, int inLeft, int inRight, int[] postorder, int postLeft, int postRight) {
        if (inLeft <= inRight) {
            int rootVal = postorder[postRight];
            TreeNode root = new TreeNode(rootVal);
            // 避免 for 循环寻找 rootVal
            int index = valToIndex.get(rootVal);
            int leftSize = index - inLeft;
            root.left = build(inorder, inLeft, inLeft + leftSize - 1,
                    postorder, postLeft, postLeft + leftSize - 1);

            root.right = build(inorder, inLeft + leftSize + 1, inRight,
                    postorder, postLeft + leftSize, postRight - 1);
            return root;
        }
        return null;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)
